<script setup lang="ts">
import type { BulletLegendItemInterface } from '@unovis/ts';
import { omit } from '@unovis/ts';
import { VisTooltip } from '@unovis/vue';
import type { Component } from 'vue';
// import { ChartTooltip } from '.';

const props = defineProps<{
  selector: string;
  index: string;
  items?: BulletLegendItemInterface[];
  valueFormatter?: (tick: number, i?: number, ticks?: number[]) => string;
  customTooltip?: Component;
}>();

// Use weakmap to store reference to each datapoint for Tooltip
function template(d: any, _i: number, _elements: Array<HTMLElement | SVGElement>) {
  const valueFormatter = props.valueFormatter ?? ((tick: number) => `${tick}`);
  if (props.index in d) {
    const omittedData = Object.entries(omit(d, [props.index]))
      .map(([key, value]) => {
        const legendReference = props.items?.find(i => i.name === key);
        return `<div>${legendReference?.name ?? key}: ${valueFormatter(value)}</div>`;
      })
      .join('');
    return `<div><strong>${d[props.index] ?? '无标题'}</strong>${omittedData}</div>`;
  } else {
    const data = d.data;
    if (!data) {
      return '';
    }
    return `<div><strong>${d[props.index] ?? '无标题'}</strong><div>${data.name}: ${valueFormatter(data[props.index])}</div></div>`;
  }
}
</script>

<template>
  <VisTooltip
    :horizontal-shift="20" :vertical-shift="20" :triggers="{
      [selector]: template,
    }"
  />
</template>
